package wviz.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import prefuse.data.Graph;
import prefuse.util.ColorLib;
import prefuse.util.ui.JValueSlider;
import wviz.gui.graph.BaseDisplay;
import wviz.gui.graph.GraphGenerator;
import wviz.gui.graph.GraphPanel;
import wviz.gui.graph.RadialDisplay;
import wviz.gui.graph.SpiderDisplay;
import wviz.gui.graph.ValueSlider;

/**
 * application main entry point
 */
public class T2vPanel extends JPanel implements ActionListener,
		FileDragAndDropCallback {

	private String fileName = "Text to Visualization";

	private int numberTermsToAnalyze = 40;
	private int graphLinks = 20;
	public static int maxWordDistance = 10;

	private static final int MAX_NUMBER_TERMS_TO_ANALYZE = 99;
	private static final int MAX_GRAPHLINKS = 99;
	private static final int MAX_WORD_DISTANCE = 20;

	private GraphPanel graphPanel;// graph display container

	private ValueSlider filterLevelSlider; // visualisation filter level
	private boolean showAsSpider = true;

	private VisualisationTask task;// perfrom visualisation task in a separate
									// thread in background
	// shows progress of visualisation
	private JProgressBar progressBar;
	// used for displaying some messages in status bar
	private JLabel statusMessage;

	// used for changing progress bar value in a linear fashion
	private Timer visualisationProgressTimer;

	// state manager create and manage menubar and toolbar states
	private StateManager stateManager;

	private BaseDisplay spiderDisplay;
	private BaseDisplay radialDisplay;

	/**
	 * Used for displaying different file formats via different packages. In
	 * most cases, it contains a JEditorPane (content member variable) to show
	 * simple html/text documents. For other types (like pdf), approperate
	 * viewer panel will be added to this panel
	 */
	private JScrollPane scrollPane;

	/**
	 * This field is responsible for creating different content viewer in right
	 * side of the main window
	 */
	// private ContentViewerManager contentViewerManager;

	/**
	 * The glass pane used for freezing visualisation graph
	 */
	private DisabledGlassPane glassPane;

	/**
	 * The toolbar of main window, items in toolbar may be added and removed by
	 * different content viewer
	 */
	private JToolBar toolbar;

	/**
	 * The specific viewer toolbar which will be added and removed when viewer
	 * changed. We just keep a refrence to it for remvoing previous viewer
	 * toolbar.
	 */
	private JComponent viewerToolbar;

	private JSplitPane splitPane;

	private JLabel fileLabel = new JLabel("        t2v");

	public T2vPanel() throws HeadlessException {

		try {
			String laf = UIManager.getSystemLookAndFeelClassName();
			UIManager.setLookAndFeel(laf);
		} catch (Exception e) {
			System.err.println("Error in setting System LookAndFeel!");
		}

		// ImageIcon appIcon = createImageIcon("icons/icon.png", "");
		// if (appIcon != null)
		// setIconImage(appIcon.getImage());

		Graph graph = GraphGenerator.pairListToGraph(createDefaultGraph());
		setGraph(graph);

		this.setLayout(new BorderLayout(2, 2));

		// contentViewerManager = new ContentViewerManager();
		// creating state manager
		stateManager = new StateManager();

		// this.setJMenuBar(stateManager.createMenuBar());

		BaseDisplay display;
		if (showAsSpider)
			display = spiderDisplay;
		else
			display = radialDisplay;

		/**
		 * fields changing when toggling between displays : display - spider or
		 * radial dataGroup - SpiderDisplay.NODES or RadialDisplay.TREE_NODES
		 * filterLabel - Search or Filter filterMaxValue - 100 or 10
		 */
		graphPanel = new GraphPanel(display, fileName,
				display.getSearchGroup(), display.getFilterLabel(),
				display.getFilterMaxValue());

		filterLevelSlider = graphPanel.getFilterLevelSlider();

		// LineBorder border =
		// (LineBorder)BorderFactory.createLineBorder(Color.gray, 1);
		CompoundBorder outBorder = new CompoundBorder(new EmptyBorder(1, 1, 1,
				1), new LineBorder(Color.gray, 1, true));
		CompoundBorder border = new CompoundBorder(outBorder, new EmptyBorder(
				10, 10, 10, 10));
		graphPanel.setBorder(border);
		graphPanel.setBackground(Color.white);

		prepareGraphDisplay();

		// creating left side of main ui
		JPanel leftPanel = new JPanel(new BorderLayout(2, 2));
		JPanel rightPanel = new JPanel(new BorderLayout());
		// rightPanel.add(this.textArea);
		leftPanel.add(graphPanel, BorderLayout.CENTER);

		// scrollPane = new JScrollPane(pasteContent);
		splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel,
				scrollPane);
		splitPane.setOneTouchExpandable(true);
		splitPane.setResizeWeight(0.5);
		splitPane.setDividerLocation(0.5);
		splitPane.setDividerSize(10);

		toolbar = stateManager.createToolbar();
		this.add(toolbar, BorderLayout.PAGE_START);
		// this.add(splitPane, BorderLayout.CENTER);
		this.add(leftPanel, BorderLayout.CENTER);
		// this.add(rightPanel, BorderLayout.EAST);
		// adding status bar
		this.add(stateManager.createStatusbar(), BorderLayout.PAGE_END);

		// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		double factor = 0.9;
		Dimension dim = new Dimension();
		dim.setSize(factor * screenSize.getWidth(),
				factor * screenSize.getHeight());
		this.setPreferredSize(dim);
		// this.setExtendedState(JFrame.MAXIMIZED_BOTH);
		Point center = new Point(
				(int) ((screenSize.getWidth() - this.getWidth()) / 2),
				(int) ((screenSize.getHeight() - this.getHeight()) / 2));
		this.setLocation(center.x - dim.width / 2, center.y - dim.height / 2);

		// this.pack();
		// create the visualisation timer
		visualisationProgressTimer = new Timer(100, this);

		glassPane = new DisabledGlassPane(graphPanel);
		// this.setGlassPane(glassPane);
	}

	public void setStatusMessageText(String text) {
		statusMessage.setText(text);
	}

	public static java.util.List<String[]> createDefaultGraph() {
		java.util.List<String[]> falseLinks = new ArrayList<String[]>(74);

		falseLinks.add(new String[] { "document", "summary" });
		falseLinks.add(new String[] { "word", "document" });
		falseLinks.add(new String[] { "document", "analysis" });
		falseLinks.add(new String[] { "document", "visualisation" });
		falseLinks.add(new String[] { "word", "visualisation" });
		falseLinks.add(new String[] { "word", "tag" });
		falseLinks.add(new String[] { "tag", "cloud" });
		falseLinks.add(new String[] { "visualisation", "tool" });
		falseLinks.add(new String[] { "visualisation", "summary" });
		falseLinks.add(new String[] { "visualisation", "by" });
		falseLinks.add(new String[] { "by", "Laurie" });
		falseLinks.add(new String[] { "Laurie", "Hirsch" });

		return falseLinks;
	}

	private class StateManager {
		OpenFileAction openFileAction;
		OpenFolderAction openFolderAction;
		StopVisualisationAction stopVisualisationAction;
		ChangeVisualisationAction changeVisualisationAction;
		SaveVisualisationAction saveVisualisationImageAction;
		AdjustmentAction adjustmentAction;
		VizEnteredTextAction textVizAction;

		public StateManager() {
			openFileAction = new OpenFileAction(T2vPanel.this);
			openFolderAction = new OpenFolderAction(T2vPanel.this);
			saveVisualisationImageAction = new SaveVisualisationAction();
			adjustmentAction = new AdjustmentAction(T2vPanel.this);

			stopVisualisationAction = new StopVisualisationAction();
			stopVisualisationAction.setEnabled(false);

			changeVisualisationAction = new ChangeVisualisationAction();
			changeVisualisationAction.setEnabled(true);
			textVizAction = new VizEnteredTextAction(T2vPanel.this);

		}

		public JToolBar createToolbar() {
			JToolBar toolBar = new JToolBar();
			toolBar.setPreferredSize(new Dimension(500, 22));
			toolBar.setFloatable(false);
			toolBar.setBackground(Color.cyan);
			toolBar.add(createToolbarButton("Open", "Open a new file",
					openFileAction, "icons/open.png"));

			toolBar.addSeparator();
			// toolBar.add(createToolbarButton("Stop", "Stop visualisation",
			// stopVisualisationAction, "icons/stop.png"));
			toolBar.add(createToolbarButton("Change", "Change Graph Type",
					changeVisualisationAction, "icons/change.png"));
			toolBar.addSeparator();
			toolBar.add(createToolbarButton("Control Panel", "Change the graph settings",
					adjustmentAction, "icons/change.png"));
			toolBar.addSeparator();
			toolBar.add(fileLabel);

			adjustmentAction.setEnabled(false);
			toolBar.add(Box.createHorizontalGlue());
			// toolBar.add(searchBox);
			return toolBar;
		}

		public JToolBar createStatusbar() {
			JToolBar statusBar = new JToolBar();
			statusBar.setPreferredSize(new Dimension(500, 22));
			statusBar.setFloatable(false);
			UIManager.put("ProgressBar.selectionBackground",
					ColorLib.getColor(0, 63, 16));
			UIManager.put("ProgressBar.selectionForeground", Color.BLACK);
			UIManager.put("ProgressBar.foreground",
					ColorLib.getColor(140, 255, 130, 80));															
			progressBar = new JProgressBar(0, 100);
			progressBar.setPreferredSize(new Dimension(300, 22));
			progressBar.setBorderPainted(true);
			progressBar.setStringPainted(true);
			statusBar.add(progressBar);
			statusBar.add(Box.createHorizontalStrut(5));
			statusMessage = new JLabel("");
			statusBar.add(statusMessage);
			statusBar.add(Box.createHorizontalStrut(5));
			statusBar.add(Box.createHorizontalGlue());
			statusBar.add(filterLevelSlider);
			filterLevelSlider.setMaximumSize(new Dimension(300, 22));
			return statusBar;
		}

		public JMenuBar createMenuBar() {
			JMenu dataMenu = new JMenu("File");
			dataMenu.add(openFileAction);
			dataMenu.add(openFolderAction);
			dataMenu.add(adjustmentAction);
			dataMenu.add(new ExitAction());

			JMenu helpMenu = new JMenu("Help");
			helpMenu.add(new HelpAction(T2vPanel.this));

			JMenuBar menubar = new JMenuBar();
			menubar.add(dataMenu);
			menubar.add(helpMenu);
			return menubar;
		}

		public void visualisationFinished() {
			stopVisualisationAction.setEnabled(false);
			changeVisualisationAction.setEnabled(true);
			openFileAction.setEnabled(true);
			openFolderAction.setEnabled(true);
			saveVisualisationImageAction.setEnabled(true);
			adjustmentAction.setEnabled(true);
		}

		public void visualisationCanceled() {
			stopVisualisationAction.setEnabled(false);
			changeVisualisationAction.setEnabled(false);
			openFileAction.setEnabled(true);
			openFolderAction.setEnabled(true);
			saveVisualisationImageAction.setEnabled(true);
			adjustmentAction.setEnabled(true);
		}

		public void visualisationStarted() {
			stopVisualisationAction.setEnabled(true);
			changeVisualisationAction.setEnabled(false);
			openFileAction.setEnabled(false);
			openFolderAction.setEnabled(false);
			saveVisualisationImageAction.setEnabled(false);
			adjustmentAction.setEnabled(false);
		}
	}

	/**
	 * Create a toolbar button
	 * 
	 * @param text
	 *            button text
	 * @param tooltip
	 *            button tooltip
	 * @param action
	 *            the actual action for performing task
	 * @param iconPath
	 *            icon path - relative from LeonardoApplication class
	 * @return a toolbar button
	 */
	public static JButton createToolbarButton(String text, String tooltip,
			Action action, String iconPath) {
		JButton button = new JButton();
		button.setBackground(Color.cyan);
		button.setAction(action);
		button.setToolTipText(tooltip);

		button.setText(text);

		return button;
	}
	
	/**
	 * Show Open File dialog for opening file or folder.
	 * 
	 * @param parent
	 * @param selectFolder
	 * @return file or folder selected by user
	 */
	public File selectFilev(Component parent, boolean selectFolder) {
		System.out.println("in selectfile ");
		String s = FileHandler.open();		
		System.out.println("length: " + s.length());
		File f = new File("test,txt");
		return f;	
	}


	private void prepareGraphDisplay() {
		BaseDisplay display;
		if (showAsSpider)
			display = spiderDisplay;
		else
			display = radialDisplay;
		graphPanel.setupDisplay(display);
		// contentViewerManager.registerClickedItemChangeListener(display);
	}

	public void changePanel() {
		showAsSpider = !showAsSpider;
		prepareGraphDisplay();
	}

	/**
	 * This method called by visualisation timer (see constructor for creating
	 * visualistion timer)
	 * 
	 * @param e
	 *            action event parameter
	 */
	public void actionPerformed(ActionEvent e) {
		int value = progressBar.getValue();
		if (value > 99) {
			progressBar.setIndeterminate(true);
		} else
			progressBar.setValue(value + 1);
	}

	public void visualisationTaskFailed(Exception e) {
		e.printStackTrace();
		visualisationProgressTimer.stop();
		progressBar.setIndeterminate(false);
		this.progressBar.setValue(0);
		this.progressBar.setString("Failed to visualise document");
		stateManager.visualisationCanceled();
		JOptionPane
				.showMessageDialog(
						this,
						"Failed to visualise document. \n "
								+ "Document may be too big or the format may not be supported \n"
								+ "Please try another document \n"
								+ "Note: PDF is not currently supported. \n"
								+ "Error " + e.getMessage(), this.fileName,
						JOptionPane.ERROR_MESSAGE);

		this.glassPane.hidePane();
	}

	/**
	 * This method called whenever visualisation task is finished. This method
	 * will stop the progress bar timer (set it to maximum)
	 * 
	 * @param g
	 *            the generated graph
	 */
	public void visualisationTaskFinished(Graph g) {
		try {
			visualisationProgressTimer.stop();
			progressBar.setIndeterminate(false);
			String sType;
			String fName;
			// if (docFile != null) {
			// sType = docFile.isFile() ? "file" : "folder";
			// fName = docFile.getName();
			// } else {
			// sType = "";
			// fName = "default";
			// }
			if (g == null) {
				this.progressBar.setValue(0);
				// String msg =
				// String.format("Can not read content of %s '%s'.",
				// sType, fName);
				String msg = "graph is null in visualisation task Finished";
				this.progressBar.setString(msg);
				JOptionPane.showMessageDialog(this, msg, this.fileName,
						JOptionPane.ERROR_MESSAGE);
			} else {
				setGraph(g);
				prepareGraphDisplay();
				this.progressBar.setValue(100);
				this.progressBar.setString("vizualization complete");
				// this.progressBar.setString(String.format(
				// "Visualisation of %s '%s' is done.", sType, fName));
			}
			stateManager.visualisationFinished();
		} catch (Exception ex) {
			ex.printStackTrace();
			statusMessage.setText("Some unknown error occured!");
			stateManager.visualisationCanceled();
		}
		this.glassPane.hidePane();
	}


	/**
	 * Create a VisualisationTask (which will be executed in the background)
	 * Also, reset progress bar and start progress timer
	 * 
	 * @param docFile
	 *            the file to be visualised
	 */
	public void visualiseStream(String fileN, InputStream stream) {
		
		System.out.println(" in vizstream0");

		if (task != null && !(task.isDone() || task.isCancelled()))
			return;
		
		fileName = fileN;
		System.out.println("filename " + fileName);

		fileLabel.setText("      " + fileName);

		task = new VisualisationTask(this, stream, numberTermsToAnalyze,
				graphLinks, this.fileName);
		setStatusMessageText("Starting visualisation ...");
		this.progressBar.setString("Visualising ");

		this.progressBar.setValue(0);
		visualisationProgressTimer.start();

		// start visualisation task
		task.execute();

		// disable (freeze) current visualisation
		glassPane.showPane();
		// update toolbar states
		stateManager.visualisationStarted();		
	}


	public void getTextFromJavaScript(String s) {
		
		System.out.println(" in gettfromjs0");

		if (task != null && !(task.isDone() || task.isCancelled()))
			return;

		task = new VisualisationTask(this, s, numberTermsToAnalyze, graphLinks);

		System.out.println("created the task");
		setStatusMessageText("Starting visualisation ...");
		this.progressBar.setString("Visualising ");

		this.progressBar.setValue(0);
		visualisationProgressTimer.start();

		// start visualisation task
		task.execute();

		// disable (freeze) current visualisation
		glassPane.showPane();
		// update toolbar states
		stateManager.visualisationStarted();
		fileLabel.setText("     pasted text");

	}

	private void visualiseIndex() {

		if (task != null && !(task.isDone() || task.isCancelled()))
			return;

		task = new VisualisationTask(this, numberTermsToAnalyze, graphLinks);
		setStatusMessageText("Starting visualisation ...");
		this.progressBar.setString("Visualising ");
		this.progressBar.setValue(0);
		visualisationProgressTimer.start();
		task.execute();

		// disable (freeze) current visualisation
		glassPane.showPane();
		// update toolbar states
		stateManager.visualisationStarted();

	}

	/**
	 * Display content of selected file. For selected folder, this method do
	 * nothing right now.
	 */
	public void displayContent(Object content) {
		// if (docFile.isDirectory()) {
		// System.out.println("Displaying folder content is not supported yet.");
		// return;
		// }

		// display content
		try {
			if (viewerToolbar != null) {
				// first remove previous viewer toolbar from main toolbar
				toolbar.remove(viewerToolbar);
			}
			// viewerToolbar = contentViewerManager.showInContainer(scrollPane,
			// docFile, searchBox, content);
			splitPane.resetToPreferredSizes();
			if (viewerToolbar != null) {
				// add new viewer toolbar to main toolbar, we need to add it
				// before search box
				int index = toolbar.getComponentCount() - 1;
				toolbar.add(viewerToolbar, index);
			}
			toolbar.invalidate();

		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, e.getMessage(),
					"Viewing Content Error", JOptionPane.ERROR_MESSAGE);
		}

	}

	private void setGraph(Graph graph) {
		showAsSpider = true;// there is a bug in StarburstLayout class, if we
							// show RadialDisplay first, we have an exception
		spiderDisplay = new SpiderDisplay(graph);
		radialDisplay = new RadialDisplay(graph);
	}

	private void cancelVisualisationTask() {
		if (task != null && !task.isDone()) {
			if (task.cancel(true)) {
				visualisationProgressTimer.stop();
				this.progressBar.setString("Visualisation canceled.");
				this.progressBar.setValue(0);
				stateManager.visualisationCanceled();
				this.glassPane.hidePane();
			}
		}
	}

	/**
	 * Stop visualsiation task, if it is not finished or canceled before
	 */
	private class StopVisualisationAction extends AbstractAction {
		public void actionPerformed(ActionEvent e) {
			T2vPanel.this.cancelVisualisationTask();
		}
	}

	private class ChangeVisualisationAction extends AbstractAction {

		public void actionPerformed(ActionEvent e) {
			T2vPanel.this.changePanel();
		}
	}

	private class SaveVisualisationAction extends AbstractAction {

		private SaveVisualisationAction() {
			this.putValue(AbstractAction.ACCELERATOR_KEY,
					KeyStroke.getKeyStroke("ctrl s"));
		}

		public void actionPerformed(ActionEvent e) {
			// delegate color to prefuse ExportDisplayAction
			BaseDisplay display;
			if (showAsSpider)
				display = spiderDisplay;
			else
				display = radialDisplay;

			// ExportDisplayAction exportActions = new ExportDisplayAction(
			// display, "Saving visualised document ...");
			// exportActions.actionPerformed(e);
		}
	}

	private class OpenFileAction extends AbstractAction {
		// private FileHandler fh= new FileHandler();

		private T2vPanel m_view;

		public OpenFileAction(T2vPanel view) {

			m_view = view;
			this.putValue(AbstractAction.NAME, "Open File...");
			this.putValue(AbstractAction.ACCELERATOR_KEY,
					KeyStroke.getKeyStroke("ctrl O"));
		}

		public void actionPerformed(ActionEvent e) {
			// File file = selectFile(m_view, false);
			// String s = selectFileToString(m_view, false);

			// stream = selectFileToStream(m_view, false);

			InputStream fis = null;
			boolean jnlp = true;
			//
			if (!jnlp) {
				try {
					//File f = new File("C:/cfp.txt");
					// File f = new
					// File("C:/Users/laurie/Documents/obama.docx");
					// File f = new
					// File("C:/Users/laurie/Documents/Cloudi.docx");
					 File f = new
					// File("C:/Users/laurie/Documents/EssentialsMetahuristics.pdf");
					// // File f = new			
					 File("C:/Users/laurie/Documents/obama.txt");
					// // File f = new
					// File("C:/Users/laurie/Documents/cloud.txt");
					fis = new FileInputStream(f);
				} catch (FileNotFoundException e2) {

					e2.printStackTrace();
				}
			
			} else {
				fis = FileHandler.openStream();		
			}

			visualiseStream(FileHandler.getName(), fis);
		}
	}

	private class VizEnteredTextAction extends AbstractAction {
		// private FileHandler fh= new FileHandler();

		private T2vPanel m_view;

		public VizEnteredTextAction(T2vPanel view) {

			m_view = view;
			this.putValue(AbstractAction.NAME, "Visualise your text...");
			this.putValue(AbstractAction.ACCELERATOR_KEY,
					KeyStroke.getKeyStroke("ctrl O"));
		}

		public void actionPerformed(ActionEvent e) {

			splitPane.resetToPreferredSizes();
			// System.out.println(pasteContent.getText());

			// InputStream str = new ByteArrayInputStream(
			// pasteContent.getText().getBytes());
			;
			// visualiseStream(str);

		}
	}

	private class OpenFolderAction extends AbstractAction {
		private T2vPanel m_view;

		public OpenFolderAction(T2vPanel view) {
			m_view = view;
			this.putValue(AbstractAction.NAME, "Open Folder...");
			this.putValue(AbstractAction.ACCELERATOR_KEY,
					KeyStroke.getKeyStroke("ctrl D"));
		}

		public void actionPerformed(ActionEvent e) {
			// File file = selectFile(m_view, true);
			// visualiseFile(file);
		}
	}

	private class ExitAction extends AbstractAction {
		public ExitAction() {
			super("Exit");
		}

		public void actionPerformed(ActionEvent e) {
			System.exit(0);
		}
	}

	private class AdjustmentAction extends AbstractAction {
		private T2vPanel m_view;

		public AdjustmentAction(T2vPanel view) {
			m_view = view;
			this.putValue(AbstractAction.NAME, "Control Panel...");
			this.putValue(AbstractAction.ACCELERATOR_KEY,
					KeyStroke.getKeyStroke("ctrl A"));
		}

		public void actionPerformed(ActionEvent e) {
			adjustmentWindow(m_view);
		}

		public String adjustmentWindow(Component c) {

			while (c != null && !(c instanceof JFrame)) {
				c = c.getParent();
			}
			final JDialog dialog = new JDialog((JFrame) c, "Control Panel",
					true);

			final JValueSlider nodeSlider = new JValueSlider(
					"High frequency words to analyse................ ", 2,
					MAX_NUMBER_TERMS_TO_ANALYZE, numberTermsToAnalyze);
			final JValueSlider linkSlider = new JValueSlider(
					"Graph links to show  ............................... ", 1,
					MAX_GRAPHLINKS, graphLinks);
			final JValueSlider distanceSlider = new JValueSlider(
					"Max distance between words for cooccurence ", 1,
					MAX_WORD_DISTANCE, maxWordDistance);

			JButton cancel = new JButton("Cancel");
			cancel.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					dialog.setVisible(false);
				}
			});
			final JButton apply = new JButton("Apply");
			apply.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("nodeSlider = " + nodeSlider.getValue());
					System.out.println("linkSlider = " + linkSlider.getValue());

					dialog.setVisible(false);

					numberTermsToAnalyze = nodeSlider.getValue().intValue();
					graphLinks = linkSlider.getValue().intValue();
					maxWordDistance = distanceSlider.getValue().intValue();

					showAsSpider = true; // TODO: apparenty star has a bug and
											// throws exception in paintAll()!
											// visualiseFile(docFile);
					visualiseIndex();
				}
			});

			JLabel title = new JLabel("Visualisation parameters:");

			Box bbox = new Box(BoxLayout.X_AXIS);
			bbox.add(Box.createHorizontalStrut(5));
			bbox.add(Box.createHorizontalGlue());
			// bbox.add(ok);
			bbox.add(Box.createHorizontalStrut(5));
			bbox.add(cancel);
			bbox.add(Box.createHorizontalStrut(5));
			bbox.add(apply);
			bbox.add(Box.createHorizontalStrut(5));

			JPanel panel2 = new JPanel(new BorderLayout());
			panel2.add(nodeSlider, BorderLayout.NORTH);
			panel2.add(linkSlider, BorderLayout.CENTER);
			panel2.add(distanceSlider, BorderLayout.SOUTH);

			JPanel panel = new JPanel(new BorderLayout());
			panel.add(title, BorderLayout.NORTH);
			panel.add(panel2, BorderLayout.EAST);
			panel.add(bbox, BorderLayout.SOUTH);
			panel.setBorder(BorderFactory.createEmptyBorder(5, 2, 2, 2));

			dialog.setContentPane(panel);
			dialog.pack();
			dialog.setLocationRelativeTo(c);
			dialog.setVisible(true);
			dialog.dispose();

			return null;
		}

	} // end AdjustmentAction() inner class

	private class HelpAction extends AbstractAction {
		public static final String HELP_CONTENT = "<html>\n"
				+ "<br/>"
				+ "<font size=+1><b>Leonardo Visualisation Tool </b></font>"
				+ "<br/>"
				+ "<br/>"
				+ "produces a graphical summary or mind map of the key features of one or more documents. <br/>"
				+ "<br/>"
				+ "<br/>"
				+ "<b>To visualise your own document:</b><br/>"
				+ "<ul>"
				+ "<li><i><font color=green>Select the File menu</font></i>"
				+ "<li><i><font color=green>Select Open File or Open Folder</font></i>"
				+ "<li><i><font color=green>Select a file or folder from your computer</font> - Currently the system supports a number of file types including Microsoft Word and PDF.<br/> Generally longer documents are likely to produce more useful visualisations.</font></i>"
				+ "</ul>"
				+ "The  visualisation should appear in a few seconds or less depending on the size and number of your document<br/>"
				+ "<br/>"
				+ "<b>Advanced</b><br/>"
				+ "Click on File menu and select control panel for options.  Use sliders to adjust the size of the visualisation.  Click on apply to see the new visualisation."
				+ "<br/>"
				+ "<br/>"
				+ "<b>Visualisation options:</b>\n"
				+ "<ul>\n"
				+ "<li><i><font color=green>choose an alternative (radial) representation</font> - Click on the \"change to radial\" button to view the radial representation. </i>\n"
				+ "<li><i><font color=green>search</font> - Enter a word or the first few letters in the search box to see matching terms</i>\n"
				+ "<li><i><font color=green>zoom</font> - on either graph type hold the mouse right click and move the mouse up or down.</i>\n"
				+ "<li><i><font color=green>spider visualisation adjustment</font> - Use the gravity slider to adjust the distance between nodes</i>\n"
				+ "<li><i><font color=green>radial visualisation adjustment</font> - Adjust the level of consecutive coonected terms using the filter level slider</i>\n"
				+ "<li><i><font color=green>radial visualisation item size adjustment</font> - Click on an item an move the mouse wheel to stretch the item</i>\n"
				+ "</ul>\n";

		private T2vPanel m_view;

		public HelpAction(T2vPanel view) {
			m_view = view;
			this.putValue(AbstractAction.NAME, "Help...");
			this.putValue(AbstractAction.ACCELERATOR_KEY,
					KeyStroke.getKeyStroke("ctrl H"));
		}

		public void actionPerformed(ActionEvent e) {
			helpWindow(m_view);

		}

		public void helpWindow(Component c) {
			showHelpWindow();
		}
	}

	public void showHelpWindow() {
		Component c = this;
		while (c != null && !(c instanceof JFrame)) {
			c = c.getParent();
		}
		final JDialog dialog = new JDialog((JFrame) c, "Help Window", true);

		final JButton ok = new JButton("OK");
		ok.setEnabled(true);
		ok.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dialog.setVisible(false);
			}
		});

		JLabel title = new JLabel(HelpAction.HELP_CONTENT);

		Box bbox = new Box(BoxLayout.X_AXIS);
		bbox.add(Box.createHorizontalStrut(5));
		bbox.add(Box.createHorizontalGlue());
		bbox.add(ok);
		bbox.add(Box.createHorizontalStrut(5));
		bbox.add(Box.createHorizontalStrut(5));

		JPanel panel = new JPanel(new BorderLayout());
		panel.add(title, BorderLayout.NORTH);
		panel.add(bbox, BorderLayout.SOUTH);
		panel.setBorder(BorderFactory.createEmptyBorder(5, 2, 2, 2));

		dialog.setContentPane(panel);
		dialog.pack();
		dialog.setLocationRelativeTo(c);
		dialog.setVisible(true);
		dialog.dispose();
	}

	@Override
	public void importFile(File file) throws IOException {
		// TODO Auto-generated method stub

	}
}